﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace Mimi.ViewModels
{
    public class BindingBase : INotifyPropertyChanged
    {
        #region Fields
        /// <summary>
        /// Event handler for property changed event
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;
        #endregion

        #region Methods
        /// <summary>
        /// Notify UI to be updated when properties has changed
        /// </summary>
        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        /// <summary>
        /// This methods set value to target field that store the value and notify to the binding control
        /// If there is no difference between target and value. Nothing happens
        /// </summary>
        /// <param name="target"></param>
        /// <param name="value"></param>
        /// <param name="propertyName"></param>
        protected void Set<T>(ref T target, T value, [CallerMemberName]string propertyName = "")
        {
            if (target == null || !EqualityComparer<T>.Default.Equals(target, value))
            {
                target = value;
                OnPropertyChanged(propertyName);
            }
        }

        /// <summary>
        /// This function notify binding object to update data.
        /// Take the caller name as parameter
        /// </summary>
        /// <param name="propertyName"></param>
        protected void NotifyChanged([CallerMemberName]string propertyName = "")
        {
            if (!string.IsNullOrEmpty(propertyName))
            {
                OnPropertyChanged(propertyName);
            }
        }
        #endregion
    }
}
